package org.butterfly.watchdog;

import org.butterfly.watchdog.task.TaskFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import javax.annotation.PreDestroy;
import java.util.Timer;
import java.util.TimerTask;

/**
 * function description
 *
 * @author drake
 * @since 2022/3/30
 */
public class WatchDog implements ApplicationRunner {
    private boolean enable = false;

    private int period = 1000;

    private int firstDelay = 1000;

    private final Timer timer = new Timer();

    @Autowired(required = false)
    private TaskFactory taskFactory;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (!enable) {
            return;
        }
        if (taskFactory == null) {
            taskFactory = TaskFactory.getDefaultFactory();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                taskFactory.doTask();
            }
        }, firstDelay, period);
    }

    @PreDestroy
    public void destroy() {
        timer.cancel();
    }

    public int getPeriod() {
        return period;
    }

    public void setPeriod(int period) {
        this.period = period;
    }

    public int getFirstDelay() {
        return firstDelay;
    }

    public void setFirstDelay(int firstDelay) {
        this.firstDelay = firstDelay;
    }

    public boolean isEnable() {
        return enable;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }
}
